<template>
  <div class="publish-container">
    <div class="publish-form">
      <h2>发布闲置商品</h2>
      <el-form 
        ref="publishForm" 
        :model="formData" 
        :rules="rules" 
        label-width="100px"
        class="form-content">
        
        <el-form-item label="商品标题" prop="title">
          <el-input 
            v-model="formData.title" 
            placeholder="请输入商品标题"
            maxlength="100"
            show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="item in categories"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="formData.price" 
            :min="0" 
            :precision="2" 
            :step="0.1"
            placeholder="请输入商品价格">
          </el-input-number>
          <span class="price-unit">元</span>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            type="textarea"
            v-model="formData.description"
            :rows="4"
            placeholder="请详细描述商品的成色、使用年限等信息"
            maxlength="1000"
            show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="商品图片" prop="imageBase64">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="handleImageUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            accept="image/jpeg,image/png,image/jpg">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><el-icon-plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('publishForm')" :loading="submitting">
            发布商品
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
 
</template>

<script>
import ProductService from '@/Services/ProductService'
import CategoryService from '@/Services/CategoryService'
import LogService from '@/Services/LogService'
import { parseJwt } from '@/utils/auth'

export default {
  name: 'PublishView',
  data() {
    // 自定义验证规则
    

    return {
      formData: {
        title: '',
        categoryId: '',
        price: 0,
        description: '',
        imageBase64: ''
      },
      imageUrl: '',
      submitting: false,
      categories: [],
      rules: {
        title: [
          { required: true, message: '请输入商品标题', trigger: 'blur' },
          { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
          { min: 10, max: 1000, message: '描述长度在 10 到 1000 个字符', trigger: 'blur' }
        ],
        imageBase64: [
          { required: true, message: '请上传商品图片', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    await this.fetchCategories()
  },
  methods: {
    // 获取分类列表
    async fetchCategories() {
      try {
        const response = await CategoryService.GetAll()
        if (response && response.$values) {
          this.categories = response.$values.filter(cat => cat.isUse === 1)
        } else if (Array.isArray(response)) {
          this.categories = response.filter(cat => cat.isUse === 1)
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        this.$message.error('获取分类失败')
      }
    },

    // 获取当前用户ID，模仿Login.vue
    getCurrentUserId() {
      const token = localStorage.getItem('token')
      if (!token) return null
      try {
        const base64Url = token.split('.')[1]
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        }).join(''))
        const payload = JSON.parse(jsonPayload)
        return payload.userId || payload.sub || payload.id || payload.nameid || payload["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]
      } catch (error) {
        console.error('解析token失败：', error)
        return null
      }
    },

    // 获取当前学号
    getCurrentStudentId() {
      const token = localStorage.getItem('token')
      if (!token) return ''
      try {
        const base64Url = token.split('.')[1]
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        }).join(''))
        const payload = JSON.parse(jsonPayload)
        // 假设学号字段为studentId或sub或name等
        return payload.studentId || payload.sub || payload.name || ''
      } catch (error) {
        console.error('解析token获取学号失败：', error)
        return ''
      }
    },

    // 生成GUID的方法
    generateGuid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },

    // 图片上传前的验证
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 处理图片上传
    handleImageUpload(options) {
      const file = options.file
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        // 移除base64字符串中的前缀（如：data:image/jpeg;base64,）
        const base64String = e.target.result.split(',')[1]
        this.formData.imageBase64 = base64String
        this.imageUrl = e.target.result
      }
    },

    // 提交表单
    async submitForm(formName) {
      // 调试：打印token和解析结果
      const token = localStorage.getItem('token')
      const decoded = this.parseJwt ? this.parseJwt(token) : (typeof parseJwt === 'function' ? parseJwt(token) : null)
      console.log('token:', token)
      console.log('decoded:', decoded)
      if (decoded) {
        console.log('userId(nameid):', decoded.nameid)
        console.log('userId(sub):', decoded.sub)
        console.log('userId(id):', decoded.id)
      }

      try {
        const valid = await this.$refs[formName].validate()
        if (!valid) {
          this.$message.error('请完善商品信息！')
          return
        }

        this.submitting = true
        const userId = this.getCurrentUserId()
        const studentId = this.getCurrentStudentId()
        console.log('最终用于请求的 userId:', userId)

        // 检查是否选择了分类
        if (!this.formData.categoryId) {
          throw new Error('请选择商品分类')
        }

        // 准备提交数据
        const submitData = {
          title: this.formData.title,
          categoryId: this.formData.categoryId,
          price: this.formData.price,
          description: this.formData.description,
          imageBase64: this.formData.imageBase64 // 使用上传的图片
        }

        // 调用后端API
        const response = await ProductService.Create(userId, submitData)
        
        if (response.code === 200) {
          // 日志记录
          try {
            await LogService.Create({
              id: this.generateGuid(),
              userId: userId,
              detail: `${studentId}发布了商品${this.formData.title}`,
              createTime: new Date().toISOString()
            })
          } catch (logError) {
            console.error('记录发布商品日志失败：', logError)
          }

          this.$message.success('商品发布成功！')
          this.$router.push('/loggedhome') // 发布成功后跳转到已登录用户的首页
        } else {
          throw new Error(response.message || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        this.$message.error(error.message || '发布失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.publish-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.publish-form {
  padding: 20px;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.form-content {
  max-width: 600px;
  margin: 0 auto;
}

.price-unit {
  margin-left: 10px;
  color: #666;
}

.el-upload__tip {
  line-height: 1.2;
  padding-top: 5px;
  color: #909399;
}

.el-form-item:last-child {
  margin-bottom: 0;
  text-align: center;
}

.el-button {
  padding: 12px 30px;
  font-size: 16px;
}

.el-button + .el-button {
  margin-left: 20px;
}

/* 自定义上传组件样式 */
:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style> 